const express = require("express");
const { db } = require("../db/mysql");
const jwt = require("jsonwebtoken");
const { tokenKey } = require("../config/config");
const route = express.Router();
// 验证
route.use("/", function (req, res, next) {
  // 验证 Token
  if (req.url === "/login" || req.url === "/register") {
    next();
    return;
  }
  token = req.headers.token;
  jwt.verify(token, tokenKey, (error, decoded) => {
    if (error) {
      res.status(204).send({ message: "身份信息过期请重新登录" });
      console.log(error);
      return;
    }
  });
  next();
});

// 登录
route.post("/login", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  db.query(`select * from user where username='${username}'`, (err, result) => {
    if (err) {
      console.log(err);
    }
    if (!result[0]) {
      res.status(404).send({ message: "用户名不存在" });
      return;
    } else if (password === result[0].password) {
      // Token 数据
      const payload = {
        name: result[0].username,
        createdAt: result[0].createdAt,
      };
      const token = jwt.sign(payload, tokenKey, { expiresIn: "7day" });
      res.status(200).send({ message: "登录成功", token, id: result[0].id });
    } else {
      res.status(201).send({ message: "密码错误" });
    }
  });
});

// 注册
route.post("/register", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  const createdAt = Date.now();
  db.query(`select * from user where username='${username}'`, (err, result) => {
    if (err) {
      console.log(err);
    }
    if (result[0]) {
      res.status(404).send({ message: "用户已存在" });
      return;
    } else {
      db.query(
        `insert into user (username,password,createdAt) values('${username}','${password}',${createdAt})`,
        (err, result) => {
          res.status(201).send({ message: "注册成功" });
        }
      );
    }
  });
});

// 签到
route.post("/sign/:id", (req, res) => {
  const id = req.params.id;
  if (!id) {
    res.status(204).send({ message: "用户不存在" });
    return;
  }
  let sql = `select * from sign where userid='${id}'`;
  db.query(sql, (err, result) => {
    if (!result[0]) {
      const At = Date.now();
      const count = 1;
      let sql = `insert into sign (userid,signAt,count) values('${id}',${At},${count})`;
      db.query(sql, (err, result) => {
        res.status(200).send({ message: "签到成功" });
      });
    } else {
      const count = result[0].count;
      const id = result[0].id;
      const signAt = result[0].signAt;
      const At = Date.now();
      const a = new Date(signAt).toDateString() === new Date().toDateString();
      if (!a) {
        let sql = `update sign set count='${
          count + 1
        }',signAt=${At} where id=${id};`;
        db.query(sql, (err, result) => {
          res.status(200).send({ message: "签到成功" });
        });
      } else {
        res.status(200).send({ message: "已签到" });
      }
    }
  });
});

// 获取签到天数
route.get("/sign/:id", (req, res) => {
  let id = req.params.id;
  sql = `select * from sign where userid='${id}'`;
  db.query(sql, (err, result) => {
    if (!result[0]) {
      res.status(200).send({ count: 0, status: false });
    } else {
      const a =
        new Date(result[0].signAt).toDateString() === new Date().toDateString();
      if (a) {
        res.status(200).send({ count: result[0].count, status: true });
      } else {
        res.status(200).send({ count: result[0].count, status: false });
      }
    }
  });
});

// 选课
route.post("/scure", (req, res) => {
  const uid = req.body.uid;
  const cid = req.body.cid;
  let sql = `select * from course where id='${cid}'`;
  db.query(sql, (err, result) => {
    status = result[0].status;
    if (status) {
      sql = `insert into clogs (cid,uid) values('${cid}','${uid}')`;
      db.query(sql, (err, result1) => {
        res.status(200).send({ message: "选课成功" });
        sql = `select count(*) as a from clogs where cid='${cid}'`;
        db.query(sql, (err, result2) => {
          if (result2[0].a == result[0].cpnumber) {
            sql = `update course set status=0 where id='${cid}'`;
            db.query(sql, () => {});
          }
        });
      });
    } else {
      res.status(201).send({ message: "课程人数已满" });
    }
  });
});

// 返回所有课程数据
route.get("/scure/:id", (req, res) => {
  let id = req.params.id;
  let sql = `select * from course`;
  db.query(sql, (err, result) => {
    for (let i = 0; i < result.length; i++) {
      result[i].csAt = getDay(result[i].csAt);
      sql = `select count(*) as a from clogs where cid='${result[i].id}'`;
      db.query(sql, (err, result1) => {
        result[i].statusNum = result1[0].a;
        sql = `select * from clogs where uid='${id}' and cid='${result[i].id}'`;
        db.query(sql, (err, result2) => {
          if (result2.length === 0) {
            result[i].select = false;
          } else {
            result[i].select = true;
          }
          if (i == result.length - 1) {
            res.status(200).send(result);
          }
        });
      });
    }
  });
});

// 添加课程
route.post("/addclass", (req, res) => {
  let { cname, cteacher, time, date, cpnumber } = req.body;
  csAt = getTime(date + " " + time);
  const sql = `insert into course (cname,cteacher,csAt,cpnumber) values('${cname}','${cteacher}','${csAt}','${cpnumber}') `;
  db.query(sql, (err, result) => {
    res.send({ message: "课程已添加" });
  });
});

// 获取课程具体信息
route.get("/getscure", (req, res) => {
  const id = req.query.id;
  const sql = `select * from course where id=${id}`;
  db.query(sql, (err, result) => {
    result[0].csAt = getDay(result[0].csAt);
    res.status(200).send(result);
  });
});

// 时间戳转换函数
function getDay(date) {
  var date = new Date(date);
  Y = date.getFullYear() + "-";
  M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  D = date.getDate() + " ";
  h = date.getHours() + ":";
  m = date.getMinutes() + "";
  s = date.getSeconds();
  return M + D + addZero(h) + addZero(m);
}

// 转换为时间戳
function getTime(time) {
  var date = new Date(time); //传入一个时间格式，如果不传入就是获取现在的时间了，这样做不兼容火狐。
  // 有三种方式获取，在后面会讲到三种方式的区别
  time1 = date.getTime();
  return time1;
}

// 补零函数
function addZero(m) {
  return m < 10 ? "0" + m : m;
}
// 导出
module.exports = route;
